import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { 
  Upload, 
  FileText, 
  Star, 
  CheckCircle, 
  Clock, 
  Download,
  Edit3,
  Trash2,
  Eye,
  Plus,
  Settings,
  Bot,
  AlertTriangle
} from "lucide-react";

// Mock data for demonstration
const mockAssignments = [
  {
    id: "ASSIGN_001",
    student_name: "Alice Johnson",
    title: "Climate Change Essay",
    submission_date: "2024-01-15T10:30:00Z",
    status: "graded",
    ai_score: 87,
    teacher_score: 85,
    confidence: 0.92,
    feedback_length: 245
  },
  {
    id: "ASSIGN_002", 
    student_name: "Bob Chen",
    title: "Historical Analysis Paper",
    submission_date: "2024-01-14T14:20:00Z",
    status: "pending_review",
    ai_score: 72,
    teacher_score: null,
    confidence: 0.78,
    feedback_length: 189
  },
  {
    id: "ASSIGN_003",
    student_name: "Carol Williams",
    title: "Science Lab Report",
    submission_date: "2024-01-13T09:15:00Z",
    status: "draft",
    ai_score: 91,
    teacher_score: null,
    confidence: 0.95,
    feedback_length: 312
  },
  {
    id: "ASSIGN_004",
    student_name: "David Brown",
    title: "Literature Review",
    submission_date: "2024-01-12T16:45:00Z",
    status: "flagged",
    ai_score: 65,
    teacher_score: null,
    confidence: 0.45,
    feedback_length: 156
  }
];

const mockRubrics = [
  {
    id: "RUB_001",
    name: "Essay Writing - Advanced",
    criteria_count: 5,
    max_points: 100,
    created_date: "2024-01-10",
    usage_count: 23
  },
  {
    id: "RUB_002",
    name: "Science Lab Report",
    criteria_count: 6,
    max_points: 100,
    created_date: "2024-01-08",
    usage_count: 15
  },
  {
    id: "RUB_003",
    name: "Historical Analysis",
    criteria_count: 4,
    max_points: 100,
    created_date: "2024-01-05",
    usage_count: 8
  }
];

const mockAIInsights = [
  {
    type: "success",
    title: "High Confidence Batch",
    description: "12 assignments graded with 90%+ confidence",
    action: "Auto-approve high-confidence grades"
  },
  {
    type: "warning",
    title: "Low Confidence Alert",
    description: "3 assignments flagged for manual review",
    action: "Review flagged submissions"
  },
  {
    type: "info",
    title: "Rubric Optimization",
    description: "Essay rubric shows consistent scoring patterns",
    action: "Consider refining unclear criteria"
  }
];

export function AIGradingAssistant() {
  const [selectedRubric, setSelectedRubric] = useState("RUB_001");
  const [activeTab, setActiveTab] = useState("assignments");
  const [uploadProgress, setUploadProgress] = useState(0);
  const [isUploading, setIsUploading] = useState(false);

  const handleFileUpload = () => {
    setIsUploading(true);
    setUploadProgress(0);
    
    // Simulate upload progress
    const interval = setInterval(() => {
      setUploadProgress(prev => {
        if (prev >= 100) {
          clearInterval(interval);
          setIsUploading(false);
          return 100;
        }
        return prev + 10;
      });
    }, 200);
  };

  const handleBulkExport = () => {
    console.log("Exporting grades and feedback...");
    // Implementation would generate bulk export
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'graded': return 'bg-green-100 text-green-800';
      case 'pending_review': return 'bg-yellow-100 text-yellow-800';
      case 'draft': return 'bg-blue-100 text-blue-800';
      case 'flagged': return 'bg-red-100 text-red-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getConfidenceColor = (confidence: number) => {
    if (confidence >= 0.9) return 'text-green-600';
    if (confidence >= 0.7) return 'text-yellow-600';
    return 'text-red-600';
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col lg:flex-row gap-4 items-start lg:items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-gray-900">Assessment Assistant</h2>
          <p className="text-gray-600 mt-1">Automate feedback and grading for written assignments with customizable rubrics</p>
        </div>
        <div className="flex gap-3">
          <Button onClick={handleBulkExport} variant="outline">
            <Download className="w-4 h-4 mr-2" />
            Export Results
          </Button>
          <Button onClick={handleFileUpload} className="bg-blue-600 hover:bg-blue-700">
            <Upload className="w-4 h-4 mr-2" />
            Upload Assignments
          </Button>
        </div>
      </div>

      {/* Quick Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Total Assignments</p>
                <p className="text-2xl font-bold">{mockAssignments.length}</p>
              </div>
              <FileText className="w-8 h-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">AI Graded</p>
                <p className="text-2xl font-bold text-green-600">{mockAssignments.filter(a => a.ai_score).length}</p>
              </div>
              <Bot className="w-8 h-8 text-green-500" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Pending Review</p>
                <p className="text-2xl font-bold text-yellow-600">{mockAssignments.filter(a => a.status === 'pending_review' || a.status === 'flagged').length}</p>
              </div>
              <Clock className="w-8 h-8 text-yellow-500" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Teacher Approved</p>
                <p className="text-2xl font-bold text-purple-600">{mockAssignments.filter(a => a.teacher_score).length}</p>
              </div>
              <CheckCircle className="w-8 h-8 text-purple-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Upload Progress */}
      {isUploading && (
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center gap-4">
              <Upload className="w-5 h-5 text-blue-500" />
              <div className="flex-1">
                <p className="text-sm font-medium">Uploading assignments...</p>
                <div className="w-full bg-gray-200 rounded-full h-2 mt-2">
                  <div 
                    className="bg-blue-600 h-2 rounded-full transition-all duration-300" 
                    style={{ width: `${uploadProgress}%` }}
                  />
                </div>
              </div>
              <span className="text-sm text-gray-600">{uploadProgress}%</span>
            </div>
          </CardContent>
        </Card>
      )}

      {/* AI Insights */}
      <Card>
        <CardHeader>
          <CardTitle>AI Insights & Recommendations</CardTitle>
          <CardDescription>Intelligent analysis and suggestions for grading workflow</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {mockAIInsights.map((insight, index) => (
              <div key={index} className="border rounded-lg p-4">
                <div className="flex items-start gap-3">
                  <div className={`w-2 h-2 rounded-full mt-2 ${
                    insight.type === 'warning' ? 'bg-yellow-500' :
                    insight.type === 'success' ? 'bg-green-500' : 'bg-blue-500'
                  }`} />
                  <div className="flex-1">
                    <h4 className="font-medium text-gray-900">{insight.title}</h4>
                    <p className="text-sm text-gray-600 mt-1">{insight.description}</p>
                    <Button variant="outline" size="sm" className="mt-2">
                      {insight.action}
                    </Button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Main Content Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-2 mb-6">
          <TabsTrigger value="assignments">Assignments</TabsTrigger>
          <TabsTrigger value="rubrics">Rubrics</TabsTrigger>
        </TabsList>

        <TabsContent value="assignments">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle>Assignment Grading Queue</CardTitle>
                  <CardDescription>Review AI-generated grades and feedback</CardDescription>
                </div>
                <Select value={selectedRubric} onValueChange={setSelectedRubric}>
                  <SelectTrigger className="w-48">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {mockRubrics.map((rubric) => (
                      <SelectItem key={rubric.id} value={rubric.id}>
                        {rubric.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Student</TableHead>
                    <TableHead>Assignment</TableHead>
                    <TableHead>AI Score</TableHead>
                    <TableHead>Teacher Score</TableHead>
                    <TableHead>Confidence</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {mockAssignments.map((assignment) => (
                    <TableRow key={assignment.id}>
                      <TableCell className="font-medium">{assignment.student_name}</TableCell>
                      <TableCell>{assignment.title}</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <span className="font-medium">{assignment.ai_score}</span>
                          <Star className="w-4 h-4 text-yellow-500" />
                        </div>
                      </TableCell>
                      <TableCell>
                        {assignment.teacher_score ? (
                          <span className="font-medium text-green-600">{assignment.teacher_score}</span>
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </TableCell>
                      <TableCell>
                        <span className={`font-medium ${getConfidenceColor(assignment.confidence)}`}>
                          {(assignment.confidence * 100).toFixed(0)}%
                        </span>
                      </TableCell>
                      <TableCell>
                        <Badge className={getStatusColor(assignment.status)}>
                          {assignment.status.replace('_', ' ')}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Button variant="outline" size="sm">
                            <Eye className="w-4 h-4" />
                          </Button>
                          <Button variant="outline" size="sm">
                            <Edit3 className="w-4 h-4" />
                          </Button>
                          {assignment.status === 'flagged' && (
                            <AlertTriangle className="w-4 h-4 text-red-500" />
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="rubrics">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle>Grading Rubrics</CardTitle>
                  <CardDescription>Create and manage rubrics for AI grading</CardDescription>
                </div>
                <Button>
                  <Plus className="w-4 h-4 mr-2" />
                  Create Rubric
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {mockRubrics.map((rubric) => (
                  <Card key={rubric.id} className="border">
                    <CardHeader>
                      <div className="flex items-start justify-between">
                        <div>
                          <CardTitle className="text-lg">{rubric.name}</CardTitle>
                          <CardDescription className="mt-1">
                            {rubric.criteria_count} criteria • {rubric.max_points} points max
                          </CardDescription>
                        </div>
                        <Button variant="outline" size="sm">
                          <Settings className="w-4 h-4" />
                        </Button>
                      </div>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-3">
                        <div className="flex items-center justify-between text-sm">
                          <span className="text-gray-600">Created</span>
                          <span>{new Date(rubric.created_date).toLocaleDateString()}</span>
                        </div>
                        <div className="flex items-center justify-between text-sm">
                          <span className="text-gray-600">Used</span>
                          <Badge variant="secondary">{rubric.usage_count} times</Badge>
                        </div>
                        <div className="flex gap-2 pt-3">
                          <Button variant="outline" size="sm" className="flex-1">
                            <Edit3 className="w-4 h-4 mr-1" />
                            Edit
                          </Button>
                          <Button variant="outline" size="sm">
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
